'use strict';

const { parseParams, parseSimpleArray } = require('../lib/utils');

module.exports = function tree_plugin(md) {
    let tree_id = 0;
    md.renderer.rules.fence_custom.tree = function(params, tokens, idx) {
        const options = parseParams(params);
        const content = tokens[idx].content.split('\n').filter(o=>!!o).map(o=>`${o.trim()}`).join('');
        tree_id++;
        let data;
        if (options.json) {
            data = (new Function('','return '+content))();
        } else {
            data = parseSimpleArray(content);
        }
        const tree_setting = {
            view: {
                dblClickExpand: false,
                showLine: true,
                showIcon: true,
                selectedMulti: false,
            },
            data: {
                key: {
                    name: 'text',
                },
            },
        };

        return `
        <ul id="mdoc_tree_${tree_id}" class="ztree"></ul>
        <script>
        $(document).ready(function(){
            $.fn.zTree.init($("#mdoc_tree_${tree_id}"), ${JSON.stringify(tree_setting)}, ${JSON.stringify(data)});
        })
        </script>
        `;
    };
};
